package com.ease.dao.statement.provider;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.core.io.Resource;

/**
 * 
 * @author nathanleewei
 * 
 */
public class ClassPathXmlStatementProvider extends AbstractMapStatementProvider {

	private static final transient Log log = LogFactory.getLog(ClassPathXmlStatementProvider.class);

	private static final SAXReader saxReader = new SAXReader();

	private Resource[] locations;

	public void populate(Document document) {
		Element rootElement = document.getRootElement();
		String namespace = rootElement.attributeValue("namespace");
		for (Object statementObject : rootElement.elements("statement")) {
			Element element = (Element) statementObject;
			String name = element.attributeValue("name");
			String statement = transform(element.getTextTrim());

			putStatement(namespace, name, statement);
		}
	}

	public void init() {
		/* OutputUtil.p("init: "+Thread.currentThread().getName()); */
		if (null == locations) {
			return;
		}
		InputStream is = null;
		Document document = null;
		for (Resource location : locations) {
			try {
				is = location.getInputStream();
			} catch (IOException e1) {
				log.error(location.getDescription() + " not found");
			}

			if (null == is) {
				return;
			}

			try {
				document = saxReader.read(is);
			} catch (DocumentException e) {
				log.error(location.getDescription() + "document not found");
			}
			if (null == document) {
				return;
			}

			populate(document);
		}
	}

	/**
	 * @return the locations
	 */
	public Resource[] getLocations() {
		return locations;
	}

	/**
	 * @param locations
	 *            the locations to set
	 */
	public void setLocations(Resource[] locations) {
		this.locations = locations;
	}

}
